/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.transas.zorlog.data.log;

import com.transas.zorlog.data.DataSource;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 *
 * @author amalikov
 */
public class TextLogSaver implements LogSaver {
	
	public TextLogSaver(String logFileName, DataSource ds) {
		this.logFileName = logFileName;
		this.ds = ds;
	}

	@Override
	public void write(ProgressInformer informer) throws FileNotFoundException, IOException {
		try {
			log = new BufferedWriter(new FileWriter(logFileName));
			init();
			for (int pos = 0; pos < ds.getSize(); ++pos) {
				doOneRow(pos);
				informer.set((int)((double)pos * 100 / ds.getSize()));
			}
		} finally {
			if (log != null)
				log.close();
		}
	}
	
	private void init() throws FileNotFoundException, IOException {
		handles = new ArrayList<>();
		
		List<String> names = ds.getNames();
		for (String s : names) {
			log.write(s);
			log.write('\t');
			handles.add(ds.getHandle(s));
		}
		log.newLine();
		log.newLine();

		nf = NumberFormat.getNumberInstance(Locale.US);
		nf.setGroupingUsed(false);
	}
	
	private void doOneRow(int pos) throws IOException {
		for (Object handle : handles) {
			log.write(ds.getValueAsString(handle, pos, nf));
			log.write('\t');
		}
		log.newLine();
	}

	private final String logFileName;
	private final DataSource ds;
	private BufferedWriter log;
	private List<Object> handles;
	private NumberFormat nf;
}
